package com.runvp.netty.runnables;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.enums.NettyCmd;
import com.runvp.common.enums.NettyType;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.netty.build.BuildHttpClint;
import com.runvp.netty.constant.NettyConstant;
import com.runvp.service.tcp.TcpService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FeeSchemeRunnable implements Runnable {

    private Channel channel;

    private TcpService tcpService;

    private MessageReceiveBody parseBody;

    public FeeSchemeRunnable(Channel channel, TcpService tcpService, MessageReceiveBody parseBody) {
        this.channel = channel;
        this.tcpService = tcpService;
        this.parseBody = parseBody;
    }

    @Override
    public void run() {
        handle(channel);
    }

    /**
     * 设备请求收费方案
     */
    public MessageResBody handles() {
        String channelId = NettyConstant.getChannelId(channel);
        String sn = NettyConstant.allOnlineChannleIds.get(channelId);
        log.info("设备请求收费方案处理channelId:{},sn:{}",channelId,sn);
        parseBody.setTerminalId(sn);
        return BuildHttpClint.postJson("/app/cmd/fee",parseBody);
    }
    /**
     * 设备发送收费方案包
     */
    public void handle(Channel channel) {
        long st = System.currentTimeMillis();
        long ast = st;
        String sn = "";
        try{
            String batchNo = System.nanoTime()+"";
            String json = JSONObject.toJSONString(parseBody);
            sn = NettyConstant.allOnlineChannleIds.get(NettyConstant.getChannelId(channel));
            log.info("设备发送收费方案包报文实体 ：{}", json);
        }catch (Exception e){
            log.error("本次设备收费方案【{}】处理异常共耗时:【{} ms】,error:{}",sn,(System.currentTimeMillis()-ast),e.getMessage());
        }finally {
            log.info("本次设备收费方案【{}】线程池内解析处理共耗时:【{} ms】",sn,(System.currentTimeMillis()-ast));
        }
    }


    /**
     * 结构结果体
     * @return str
     */
    private JSONObject buildBody(){
        JSONObject map = new JSONObject();
        map.put("pr1","0.5");
        map.put("pr2","0.6");
        map.put("pr3","0.7");
        map.put("pr4","0.8");
        map.put("pr5","0.9");
        map.put("pr6","1");
        map.put("pr7","1.1");
        map.put("pr8","1.2");
        map.put("pr9","1.3");
        map.put("pr0","1.4");
        return map;
    }


    /**
     * 默认报文
     *
     * @return MessageResBody
     */
    public MessageResBody defaultRes() {
        MessageResBody resBody = new MessageResBody(NettyType.SERVER_RECEIVE_DEVICE.getCode(), NettyCmd.SERVER_RES_FEE_SCHEME.getCode());
        resBody.setDid("000000000000");
        resBody.setVersion("01");
        resBody.setBodyJson(buildBody()).buildRes();
        log.info("服务器组装收费方案报文完毕");
        return resBody;
    }

}
